package com.open.exam.businessservice;

import com.open.exam.common.OperationResult;
import com.open.exam.common.ReturnData;
import com.open.exam.databasemodel.ExamPlanInfo;
import com.open.exam.databasemodel.ExamingMonitor;
import com.open.exam.databasemodel.FreeExamReport;
import com.open.exam.databasemodel.PackageExamReportResult;
import com.open.exam.dto.AdminInfo;
import com.open.exam.dto.ExamingMonitorViewModel;
import com.open.exam.dto.FreeExamExamineeInfo;
import com.open.exam.enums.ExamResultUploadState;
import com.open.exam.enums.OperationResultType;
import com.open.exam.enums.TestPaperSubmitType;
import com.open.exam.mapper.FreeExamReportMapper;
import com.open.exam.service.*;
import com.open.exam.utils.DateUtil;
import com.open.exam.utils.GsonUtil;
import com.open.exam.utils.HttpRequestUtils;
import com.open.exam.utils.ListUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description TODO
 * @author 奶茶
 * Created by on 2019/2/18 14:27.
 */
@Service
public class TimedTaskBusinessService {

    private static Logger logger = LoggerFactory.getLogger(TimedTaskBusinessService.class);

    @Value("${ExamSiteURL}")
    private String examSiteURL;

    @Autowired
    private ExamPlanInfoService examPlanInfoService;
    @Autowired
    private ExamSubjectService examSubjectService;
    @Autowired
    private ExamReportBusinessService examReportBusinessService;
    @Autowired
    private ExaminerArrangeService arrangeService;
    @Autowired
    private ExamReportService examReportService;
    @Autowired
    private ExamMonitorService monitorService;
    @Autowired
    private FreeExamReportMapper freeExamReportMapper;

    /**
     * 自动构建已结束场次的考试结果包
     */
    public String buildExamResultPackageTimedTask(){

        //获取所有已导入且已开始的批次信息
        List<ExamPlanInfo> allStartExamPlanInfo = examPlanInfoService.findAllStartExamPlanInfo();
        //虚拟信息
        AdminInfo adminInfo = new AdminInfo();
        if(!ListUtil.isEmpty(allStartExamPlanInfo)){
            allStartExamPlanInfo.forEach(examPlanInfo -> {
                //查询批次下所有科目及场次信息
                List<String> allExamSubjectID = examSubjectService.findAllExamSubjectIDBYExamPlanID(examPlanInfo.getExamPlanInfoID());
                String examPlanInfoID = examPlanInfo.getExamPlanInfoID();
                String appID = examPlanInfo.getAppID();
                String examSiteID = examPlanInfo.getExamSiteID();
                adminInfo.setExamSiteID(examSiteID);
                adminInfo.setAppName(appID);
                adminInfo.setExamSiteName(examSiteID);
                allExamSubjectID.forEach(examSubjectID -> {
                    //判断当前批次下的当前科目是否有未结束的场次
                    Integer count = arrangeService.findArrangeInfoBYPlanIDANDSubjectID(examPlanInfoID, examSubjectID);
                    //判断当前批次下的当前科目是否已生成考试结果包
                    Boolean aBoolean = examReportService.getExamReportCountBYExamPlanIDANDExamSubjectID(examPlanInfoID, examSubjectID);
                    if(count == null && aBoolean){
                        //count为null标示当前科目下的所有场次均已结束 可以生成结果包
                        List<ExamingMonitorViewModel> freeExamReportList = examReportBusinessService.findFreeExamReportList(appID, examPlanInfoID, examSubjectID, examSiteID, null, null);
                        List<FreeExamExamineeInfo> list = new ArrayList<>();
                        if(!freeExamReportList.isEmpty()){
                            freeExamReportList.forEach(examingMonitorViewModel -> {
                                FreeExamExamineeInfo examineeInfo = new FreeExamExamineeInfo();
                                examineeInfo.setExamineeId(examingMonitorViewModel.getExamineeID());
                                examineeInfo.setSceneId(examingMonitorViewModel.getExamSceneID());
                                examineeInfo.setRoomId(examingMonitorViewModel.getExamRoomID());
                                examineeInfo.setSubjectId(examSubjectID);
                                list.add(examineeInfo);
                            });
                        }
                        try {
                            OperationResult operationResult = examReportBusinessService.freeExamInfo(appID, examSiteID, examPlanInfoID, list, adminInfo);
                            PackageExamReportResult packageExamReportResult = new PackageExamReportResult(appID, examSiteID, examPlanInfoID, examSubjectID, operationResult.getResultType().name(), operationResult.getMessage());
                            //插入打包结果
                            examReportService.insertPackageExamReportResult(packageExamReportResult);
                            if(operationResult.getResultType().equals(OperationResultType.Success)){
                                FreeExamReport freeExamReport = (FreeExamReport) operationResult.getAppendData();
                                //打包成功 通知考务
                                String result = HttpRequestUtils.send_UnirestRecoredSaving_post(examSiteURL, "/examplan/resultpackage/web/" + examPlanInfoID + "?examResultUrl=" + freeExamReport.getExamResult(), null, null);
                                ReturnData returnData = GsonUtil.fromJsonToObject(result, ReturnData.class);
                                if(returnData.getSuccess()){
                                    //上传成功  修改结果包状态为已上传
                                    freeExamReport.setIfUpload(ExamResultUploadState.Uploaded.getPrefix().shortValue());
                                    freeExamReportMapper.updateIncludeInfo(freeExamReport);
                                }
                            }
                        } catch (Exception e) {
                            logger.error("生成计划包异常！批次ID：" + examPlanInfoID + "-----科目ID：" + examSubjectID,e);
                        }
                    }
                });
            });
        }
        return OperationResultType.Success.getDisplay();
    }

    /**
     * 提交当前超时未交卷的考生
     * @return
     */
    public String submitPaperByOvertime(){
        //查询所有已开考状态未交卷的考生监控信息
        List<ExamingMonitor> submitPaperInfo = monitorService.findAllUNSubmitPaperInfo();
        if(!ListUtil.isEmpty(submitPaperInfo)){
            submitPaperInfo.forEach(examingMonitor -> {
                //获取当前时间与考生开考时间的差
                Long timeDifference = DateUtil.getTimeDifference(new Date(), DateUtil.convertStringToDate(examingMonitor.getExamStartTime()));
                if(timeDifference > examingMonitor.getRetainTime()){
                    //已结束->未交卷->系统修改该状态
                    examingMonitor.setRetainTime(0);
                    examingMonitor.setSubmitType(TestPaperSubmitType.SystemAutoSubmit.getPrefix().shortValue());
                    //0未开考；1已登录；2已开考未交卷；3已交卷；4作废；5试卷下载完成；6意外处理作废
                    examingMonitor.setSysState(Short.valueOf("3"));
                    monitorService.updateExamingMonitorSubmitANDSysState(examingMonitor);
                }
            });
            return OperationResultType.Success.getDisplay();
        }
        return null;
    }
}
